package com.wang.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.common.utils.PageUtils;
import com.wang.common.utils.Query;
import com.wang.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.wang.gulimall.product.dao.AttrDao;
import com.wang.gulimall.product.dao.AttrGroupDao;
import com.wang.gulimall.product.dao.CategoryDao;
import com.wang.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.wang.gulimall.product.entity.AttrEntity;
import com.wang.gulimall.product.entity.AttrGroupEntity;
import com.wang.gulimall.product.entity.CategoryEntity;
import com.wang.gulimall.product.service.AttrService;
import com.wang.gulimall.product.service.CategoryService;
import com.wang.gulimall.product.vo.AttrRespVO;
import com.wang.gulimall.product.vo.AttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存商品属性时，需在商品属性-属性分组表中保存该条关系
     * @param attr
     */
    @Override
    public void saveDetail(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        //将attr中的属性拷贝给attrEntity中有的属性
        BeanUtils.copyProperties(attr, attrEntity);
        //向pms_attr表中保存数据
        this.save(attrEntity);
        //保存成功后需在pms_attr_attrgroup_relation表中更新
        //1.13更新前需进行判定，如果该属性没有在此表中，那么就不更新
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
        attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
        attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
        QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_id",attrEntity.getAttrId());
        Integer integer = attrAttrgroupRelationDao.selectCount(queryWrapper);
        if (integer != 0){
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    @Override
    public PageUtils getBaseAttrList(Map<String, Object> parms, Long catelogId, String type) {
        IPage<AttrEntity> page = new Query<AttrEntity>().getPage(parms);
        //设置查询条件
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_type", "base".equalsIgnoreCase(type) ? 1 : 0);
        if (catelogId != 0) {
            wrapper.eq("catelog_id", catelogId);
        }
        String key = (String) parms.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wrapper.eq("attr_id", key).or().like("attr_name", key);
        }
        this.page(page, wrapper);
        //查询出来的列表
        List<AttrEntity> records = page.getRecords();
        List<Object> collect = records.stream().map(attrEntity -> {
            AttrRespVO attrRespVO = new AttrRespVO();
            //拷贝
            BeanUtils.copyProperties(attrEntity, attrRespVO);

            //设置groupName 所属分组名字
            QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("attr_id", attrEntity.getAttrId());
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(queryWrapper);
            if (attrAttrgroupRelationEntity != null){
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                if (attrGroupEntity != null) {
                    attrRespVO.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            //设置catelogName 所属分类名字
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            attrRespVO.setCatelogName(categoryEntity.getName());

            return attrRespVO;
        }).collect(Collectors.toList());

        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(collect);
        return pageUtils;
    }

    /**
     * 根据attrId查询AttrVo信息
     * @param attrId
     * @return
     */
    @Override
    public AttrRespVO getDetailInfo(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        AttrRespVO attrRespVO = new AttrRespVO();
        BeanUtils.copyProperties(attrEntity, attrRespVO);
        QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_id", attrId);
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(queryWrapper);
        if (attrAttrgroupRelationEntity != null) {
            //设置attrGroupId
            attrRespVO.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
        }
        CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
        if (categoryEntity != null) {
            //设置CatelogPath
            Long[] parentID = categoryService.getCatelogIds(categoryEntity.getCatId());
            attrRespVO.setCatelogPath(parentID);
        }
        return attrRespVO;
    }

    /**
     * 保存修改后的商品属性
     * @param attr
     */
    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        //保存基本信息
        this.updateById(attrEntity);
        //保存关联关系
        AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
        entity.setAttrGroupId(attr.getAttrGroupId());
        QueryWrapper<AttrAttrgroupRelationEntity> updateWrapper = new QueryWrapper<>();
        updateWrapper.eq("attr_id", attr.getAttrId());
        //如果没有表中没有数据，那就添加
        Integer count = attrAttrgroupRelationDao.selectCount(updateWrapper);
        if (count>0){
            //表中有数
            attrAttrgroupRelationDao.update(entity, updateWrapper);
        }else {
            entity.setAttrId(attr.getAttrId());
            attrAttrgroupRelationDao.insert(entity);
        }

    }

    /**
     * 根据attrgroupId获取所有的attr
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getAttrRelation(Long attrgroupId) {
        //根据attrgroupId去关系表中查所所有的attrid
        QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_group_id", attrgroupId);
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationDao.selectList(queryWrapper);
        List<Long> longList = attrAttrgroupRelationEntities.stream().map(attrAttrgroupRelationEntity -> {
            return attrAttrgroupRelationEntity.getAttrId();
        }).collect(Collectors.toList());
        if (longList == null || longList.size() ==0){
            return null;
        }
        Collection<AttrEntity> attrEntities = this.listByIds(longList);
        return (List<AttrEntity>) attrEntities;
    }

}